package com.inspur.edp.cef.variable.core.data;


import com.inspur.edp.cef.api.buffer.ICefBuffer;
import com.inspur.edp.cef.api.changeListener.EntityDataChangeListener;
import com.inspur.edp.cef.api.dataType.base.IAccessorCreator;
import com.inspur.edp.cef.api.session.ICefSessionItem;
import com.inspur.edp.cef.core.buffer.base.CefBuffer;
import com.inspur.edp.cef.entity.accessor.base.IAccessor;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import com.inspur.edp.cef.variable.api.data.IVariableData;

import java.util.Map;

public class BufferManager
{
	private ICefSessionItem privateSessionItem;
	protected final ICefSessionItem getSessionItem()
	{
		return privateSessionItem;
	}

	private IAccessorCreator privateCreator;
	protected final IAccessorCreator getCreator()
	{
		return privateCreator;
	}

	protected BufferManager(ICefSessionItem sessionItem, IAccessorCreator creator)
	{
		DataValidator.checkForNullReference(sessionItem, "sessionItem");
		DataValidator.checkForNullReference(creator, "creator");

		privateSessionItem = sessionItem;
		privateCreator= creator;
	}

	protected final IAccessor InitBuffer_ZeroLevel(IVariableData data, boolean isReadonly)
	{
		IAccessor accessor = CreateAccessor(data, isReadonly);
		getSessionItem().getVariableBuffers().put(0,new CefBuffer(accessor));
		return accessor;
	}

	protected final IAccessor InitNextBuffer(boolean isReadonly)
	{
		if (getSessionItem().getVariableBuffers() == null || getSessionItem().getVariableBuffers().size() == 0)
		{
			throw new UnsupportedOperationException();
		}

		int maxLevel =getMaxLevel(getSessionItem().getVariableBuffers()) ;//.Max(pair => pair.getKey());
		IAccessor accessor = CreateAccessor((IVariableData)getSessionItem().getVariableBuffers().get(maxLevel).getData(), isReadonly);
		getSessionItem().getVariableBuffers().put(maxLevel + 1 ,new CefBuffer(accessor));
		return accessor;
	}

	private  Integer getMaxLevel(Map<Integer, ICefBuffer> buffers)
	{
		if(buffers==null||buffers.size()==0)
			return 0;
		Integer i =0;
		for (Map.Entry<Integer ,ICefBuffer> item:buffers.entrySet())
		{
			if(item.getKey()>i)
				i=item.getKey();
		}
		return i;
	}

//C# TO JAVA CONVERTER TODO TASK: Lambda expressions and anonymous methods are not converted by C# to Java Converter:
	protected IAccessor GetDataByLevel(int level)
	{
		ICefBuffer buffer=GetBufferByLevel(level);
		if(buffer==null)
			return null;
		return buffer.getData();
	}

//C# TO JAVA CONVERTER TODO TASK: Lambda expressions and anonymous methods are not converted by C# to Java Converter:
	private IAccessor CreateAccessor(IVariableData data, boolean isReadonly) {
	if(isReadonly)
		return getCreator().createReadonlyAccessor(data);
	else
		return getCreator().createAccessor(data);
	}

	private ICefBuffer GetBufferByLevel(int level)
	{
		return getSessionItem().getVariableBuffers().get(level);
	}

	public EntityDataChangeListener Listener()
	{return getSessionItem().getVarListener();}
}